package com.easy.carpanel.ui;

import android.Manifest;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.easy.carpanel.R;
import com.easy.carpanel.service.MessageEvent;
import com.easy.carpanel.uart.uartJni;
import com.easy.carpanel.until.CarUtil;
import com.easy.carpanel.view.TextProgressBar;
import com.tbruyelle.rxpermissions2.RxPermissions;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

import androidx.appcompat.app.AppCompatActivity;
import butterknife.BindView;
import butterknife.ButterKnife;
import io.reactivex.functions.Consumer;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class BmpActivity extends AppCompatActivity {

    int   pressurevaule=0; //压强参数
    int   incartemp = 0 ;    //室内温度
    int    speed   = 0X5A ; //  速度


    @BindView(R.id.txt2)
    TextView txt2;
    @BindView(R.id.txt1)
    TextView txt1;
    @BindView(R.id.img_weather)
    ImageView imgWeather;       //天气
    @BindView(R.id.asl_num)
    TextView aslNum;            //海拔
    @BindView(R.id.addressTextView)
    TextView addressTextView;
    @BindView(R.id.txt_time)
    TextView txtTime;
    @BindView(R.id.txt_date)
    TextView txtDate;
    Timer timer;
    TimerTask task;
    @BindView(R.id.bar1)
    TextProgressBar bar1;    //速度进度条
    @BindView(R.id.bar2)
    TextProgressBar bar2;    //温度进度条

    @BindView(R.id.yqtextview)
    TextView  yqtextview;    //压强
    @BindView(R.id.intempTextView)
    TextView   intempTextView; //室内温度


    private boolean isFristWeather = true;

    //声明AMapLocationClient类对象
    public AMapLocationClient mLocationClient = null;
    //声明AMapLocationClientOption对象
    public AMapLocationClientOption mLocationOption = null;

    private Runnable readerRunnable;
    byte[] read_buf = new byte[1024];
    Handler handler = new Handler();
    int fd;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bmp);
        ButterKnife.bind(this);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);


        //初始化定位
        mLocationClient = new AMapLocationClient(getApplicationContext());
        //设置定位回调监听
        mLocationClient.setLocationListener(mLocationListener);
        //初始化AMapLocationClientOption对象
        mLocationOption = new AMapLocationClientOption();
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        mLocationClient.setLocationOption(mLocationOption);
        final RxPermissions rxPermissions = new RxPermissions(this);
        rxPermissions
                .request(Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION).subscribe(new Consumer<Boolean>() {
            @Override
            public void accept(Boolean aBoolean) throws Exception {
                if (aBoolean) {
                    //申请的权限全部允许
                    //给定位客户端对象设置定位参数
                    mLocationClient.setLocationOption(mLocationOption);
                    //启动定位
                    mLocationClient.startLocation();

                } else {
                    //只要有一个权限被拒绝，就会执行
                    Toast.makeText(BmpActivity.this, "GPS定位权限没有打开，请打开！", Toast.LENGTH_SHORT).show();
                }
            }
        });

        yqtextview.setText(pressurevaule+"hpa");
        intempTextView.setText(incartemp+"℃");
        // 测试代码 TODO
        int v1 = new Random().nextInt(100);
        txt1.setText(speed+"");
        bar1.setCurrent(speed);
        bar1.setProgress(speed/5);
//        txt2.setText((int)(v1*0.4-10)+" ℃");
//        bar2.setCurrent((int)(v1*0.4-10));
//        bar2.setProgress(v1);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(MessageEvent event) {
        if (event.message.equals("bmptime")) {
            Date date = new Date(System.currentTimeMillis());
            SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm");
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd E");
            txtTime.setText(timeFormat.format(date));
            txtDate.setText(dateFormat.format(date));
        }
    }

    @Override
    public void onStart() {
        super.onStart();
        EventBus.getDefault().register(this);
        timer = new Timer();
        task = new TimerTask() {
            @Override
            public void run() {
                EventBus.getDefault().post(new MessageEvent("bmptime"));
            }
        };
        timer.schedule(task, 0, 1000);
    }


    @Override
    public void onStop() {
        super.onStop();
        if (timer != null) {
            timer.cancel();
            if (task != null) {
                task.cancel();
            }
        }
        EventBus.getDefault().unregister(this);
    }


    @Override
    protected void onResume() {
        String device = "/dev/ttyS4";
        fd = uartJni.open(device, 115200);
        Log.d("jiangyunwei", "open the device of " + device + ", fd is: " + fd);

        readerRunnable = new Runnable() {
            @Override
            public void run() {
                int read_count = uartJni.read(fd, read_buf, read_buf.length);

                if (read_count < 0) {
                    read_count = 0;
                }
                String  value =  CarUtil.toHex(read_buf, read_count);
                Log.d("jiangyunwei",value);
                System.out.println(value);
                List<String> list = CarUtil.getStrList(value,2);
                if(list==null || list.size()<=8){
                    handler.postDelayed(this, 1000);
                    return;
                }
                speed =  (int) Long.parseLong(list.get(0),  16);
                pressurevaule =  (int) Long.parseLong(list.get(4),  16);
                incartemp =  (int) Long.parseLong(list.get(5),  16);
                yqtextview.setText(pressurevaule+"hpa");
                intempTextView.setText(incartemp+"℃");
                txt1.setText(speed +"");
                bar1.setCurrent(speed);
                bar1.setProgress(speed/5);
                handler.postDelayed(this, 1000);
                                    //相当于定时器，每隔1s执行一次该线程
            }
        };
        handler.post(readerRunnable);

        super.onResume();
    }

    @Override
    protected void onPause() {
        uartJni.close(fd);
        handler.removeCallbacks(readerRunnable);
        super.onPause();
    }


    //声明定位回调监听器
    public AMapLocationListener mLocationListener = new AMapLocationListener() {
        @Override
        public void onLocationChanged(AMapLocation aMapLocation) {
            aslNum.setText(aMapLocation.getAltitude() + "米");
            System.out.println(aMapLocation.getAltitude() + "米");
            addressTextView.setText(aMapLocation.getAddress());

            if (isFristWeather) {
                isFristWeather = false;
                OkHttpClient client = new OkHttpClient();
                String url = "https://restapi.amap.com/v3/weather/weatherInfo?" + "key=0ccb4f953a8b57bab10919ec97c18b2a&city=" + aMapLocation.getAdCode();
                Request request = new Request.Builder().get()
                        .url(url)
                        .build();
                Call call = client.newCall(request);
                call.enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {

                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        //一般会得到Json数据，这时候就要用Json解析的一系列方法处理了，网上都可查这里不多讲
                        String jsonString = response.body().string();
                        //把访问url得到的数据打印出来
                        JSONObject json = JSONObject.parseObject(jsonString);
                        JSONArray livejson = json.getJSONArray("lives");
                        if (livejson == null) {
                            return;
                        }
                        String weather = livejson.getJSONObject(0).getString("weather");
                        String temperature = livejson.getJSONObject(0).getString("temperature");
                        BmpActivity.this.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                txt2.setText(temperature + "℃");
                                bar2.setCurrent(Integer.parseInt(temperature));
                                bar2.setProgress((int)((Float.parseFloat(temperature)+10)/0.4));
                            }
                        });
                        if (weather.contains("晴")) {
                            BmpActivity.this.runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    imgWeather.setImageResource(R.mipmap.qing);
                                }
                            });
                        }
                        if (weather.contains("多云")) {
                            BmpActivity.this.runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    imgWeather.setImageResource(R.mipmap.duoyun);
                                }
                            });

                        }
                        if (weather.contains("阴")) {
                            BmpActivity.this.runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    imgWeather.setImageResource(R.mipmap.yin);
                                }
                            });

                        }
                    }
                });
            }


        }
    };


}
